package net.oschina.allchat.server.framework.core.commons.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IoUtils {

    private static final Logger logger = LoggerFactory.getLogger(IoUtils.class);

    public static void closeIO(InputStream in) {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to close the stream.", e);
                }
            }
        }
    }

    public static void closeIO(OutputStream out) {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to close the stream.", e);
                }
            }
        }
    }

    public static boolean deleteFileRecursively(File file) {
        if (!file.isDirectory()) {
            return file.delete();
        } else {
            for (File subFile : file.listFiles()) {
                if (!deleteFileRecursively(subFile)) {
                    return false;
                }
            }

            return file.delete();
        }
    }

    public static void closeIO(Writer writer) {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to close the writer.", e);
                }
            }
        }
    }

    public static void closeIO(Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to close the reader.", e);
                }
            }
        }
    }

    public static void writeToFile(File file, String content) throws IOException {
        FileWriter out = null;
        try {
            out = new FileWriter(file);
            out.write(content);
        } catch (IOException e) {
            throw e;
        } finally {
            IoUtils.closeIO(out);
        }
    }
}
